<template>
  <div>
    <CommonPanel :title="$t('portalAuth.baseSetting')">
      <a-form-model
        ref="portalForm"
        :rules="rules"
        :model="portalForm"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        labelAlign="left"
        :colon="false"
      >
        <!-- customize -->
        <a-form-model-item
          :label="$t('portalAuth.portalName')"
          prop="portalName"
        >
          <a-input style="width: 320px" v-model="portalForm.portalName" />
        </a-form-model-item>
        <a-form-model-item
          :label="$t('portalAuth.loginOption')"
          prop="authType"
        >
          <a-checkbox-group
            @change="onChangeAuthType"
            v-model="portalForm.authType"
            class="auth-type-cbx"
          >
            <div class="loginOption" style="display: grid">
              <a-checkbox defaultChecked value="PASS" name="authType">
                {{ $t('portalAuth.onClick') }}
              </a-checkbox>
              <div
                v-show="portalForm.authType.includes('PASS')"
                class="sub-form"
              >
                <a-form-model-item
                  :label-col="{ span: 7 }"
                  :wrapper-col="{ span: 17 }"
                  :label="$t('portalAuth.accessDuration')"
                >
                  <a-radio-group v-model="portalForm.accessTime">
                    <a-radio :value="0">
                      {{ $t('userManage.unlimited') }}
                    </a-radio>
                    <a-radio :value="15"> 15 </a-radio>
                    <a-radio :value="30"> 30 </a-radio>
                    <a-radio :value="60"> 60 </a-radio>
                    <a-radio :value="-1">
                      {{ $t('userManage.custom') }}
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
                <a-form-model-item
                  :label-col="{ span: 7 }"
                  :wrapper-col="{ span: 17 }"
                  :label="$t('portalAuth.customedDuration')"
                  prop="accessTimeVal"
                  v-show="portalForm.accessTime === -1"
                >
                  <a-input
                    v-model="portalForm.accessTimeVal"
                    placeholder="1-720"
                  />
                </a-form-model-item>
                <a-form-model-item
                  :label-col="{ span: 7 }"
                  :wrapper-col="{ span: 17 }"
                  v-if="portalForm.accessTime != '0'"
                  :label="$t('portalAuth.accessTime')"
                >
                  <a-select
                    v-model="portalForm.limitedTimes"
                    placeholder="$t('portalAuth.accessTime2')"
                    style="width: 320px"
                  >
                    <a-select-option :value="0">
                      {{ $t('userManage.unlimited') }}
                    </a-select-option>
                    <a-select-option :value="1"> 1 </a-select-option>
                    <a-select-option :value="2"> 2 </a-select-option>
                    <a-select-option :value="3"> 3 </a-select-option>
                    <a-select-option :value="4"> 4 </a-select-option>
                    <a-select-option :value="5"> 5 </a-select-option>
                    <a-select-option :value="6"> 6 </a-select-option>
                    <a-select-option :value="7"> 7 </a-select-option>
                    <a-select-option :value="8"> 8 </a-select-option>
                    <a-select-option :value="9"> 9 </a-select-option>
                    <a-select-option :value="10"> 10 </a-select-option>
                  </a-select>
                </a-form-model-item>
              </div>
              <a-checkbox value="FIXACCOUNT" name="authType">
                {{ $t('portalAuth.account') }}
              </a-checkbox>
              <a-checkbox value="VOUCHER" name="authType">
                {{ $t('portalAuth.voucher') }}
              </a-checkbox>
              <a-checkbox value="SMS" name="authType">
                {{ $t('portalAuth.sms') }}
              </a-checkbox>
              <div
                v-show="portalForm.authType.includes('SMS')"
                class="sub-form"
              >
                <a-form-model-item
                  :label-col="{ span: 7 }"
                  :wrapper-col="{ span: 17 }"
                  :label="$t('twilio.sid')"
                >
                  <span>{{ portalForm.sid }}</span>
                </a-form-model-item>
                <a-form-model-item
                  :label-col="{ span: 7 }"
                  :wrapper-col="{ span: 17 }"
                  :label="$t('twilio.token')"
                >
                  <span>{{ portalForm.authToken }}</span>
                </a-form-model-item>
                <a-form-model-item
                  :label-col="{ span: 7 }"
                  :wrapper-col="{ span: 17 }"
                  :label="$t('twilio.phone')"
                >
                  <span>{{ portalForm.authPhone }}</span>
                </a-form-model-item>
              </div>
              <a-checkbox value="REGISTER" name="authType">
                {{ $t('portalAuth.registerAuth') }}
              </a-checkbox>

              <!-- <a-checkbox disabled value="FACEBOOK" name="authType">
                {{ $t('portalAuth.facebookAccount') }}
                <a-tooltip
                  placement="right"
                  :title="$t('portalAuth.facebookTips1')"
                  :auto-adjust-overflow="false"
                >
                  <icon-font type="ic-notice" />
                </a-tooltip>
              </a-checkbox> -->
            </div>
          </a-checkbox-group>
        </a-form-model-item>
        <a-form-model-item :label="$t('portalAuth.showBalance')">
          <a-switch v-model="portalForm.displayStatistics" />
        </a-form-model-item>
        <a-form-model-item
          :label="$t('portalAuth.postLoginUrl')"
          prop="redirectUrl"
        >
          <a-input v-model="portalForm.redirectUrl" />
        </a-form-model-item>
      </a-form-model>
    </CommonPanel>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import CommonPanel from './commonPanel';
import { ValiDateTools } from '@utils/index';
import { getByteLength } from '@/utils';
export default {
  name: 'portalAuthEditor',
  props: {
    portalObj: {
      typeof: Object,
      default: null,
    },
  },

  data() {
    return {
      subform1: {}, //表单数据
      editedPortalName: null,
      portalForm: {
        portalName: '', // portal name
        authType: ['PASS'], // login option
        accessTime: 0, // authType是PASS的时候 Access Duration (Min)
        accessTimeVal: 60, // authType是PASS的时候 customed Access Duration (Min)
        limitedTimes: 0, // authType是PASS的时候
        displayStatistics: false, // show balance page
        redirectUrl: 'https://www.ruijienetworks.com', // post login url
        sid: '', // authType是SMS的时候
        authToken: '', // authType是SMS的时候
        authPhone: '', // authType是SMS的时候
      },
      rules: {
        authType: [
          {
            validator: (rule, value, callback) => {
              if (value.length === 0) {
                return callback(this.$t('common.mustEnter'));
              }

              if (value.includes('SMS')) {
                if (
                  !this.portalForm.sid ||
                  !this.portalForm.authToken ||
                  !this.portalForm.authPhone
                ) {
                  return callback(new Error(this.$t('portalAuth.smsTip')));
                }
              }

              return callback();
            },
            trigger: 'change',
          },
        ],
        redirectUrl: [
          {
            validator: (rule, value, callback) => {
              if (value && !ValiDateTools.urlRegex.test(value)) {
                return callback(this.$t('common.correctUrl'));
              }
              return callback();
            },
            trigger: 'blur',
          },
        ],
        portalName: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(this.$t('common.mustEnter'));
              }
              let length = getByteLength(value);
              if (length > 64) {
                callback(new Error(this.$t('userManage.commentLengthTip')));
              }
              const portals = this.$store.state.PortalAuth.portals;
              for (const p of portals) {
                if (value === p.name && value !== this.editedPortalName) {
                  callback(
                    new Error(this.$t('portalAuth.portalNameRepeatTip'))
                  );
                }
              }

              return callback();
            },
            trigger: 'blur',
          },
        ],
        accessTimeVal: [
          {
            validator: (rule, value, callback) => {
              if (this.portalForm.accessTime !== -1) {
                return callback();
              }

              if (typeof value == 'string' && value.trim() === '') {
                return callback(new Error(this.$t('common.mustEnter')));
              }
              let num = Number(value);
              if (!/(^[1-9]([0-9]*)$|^[0-9]$)/.test(value)) {
                return callback(new Error(this.$t('common.onlyInt')));
              }
              if (1 <= num && num <= 720) {
                return callback();
              } else {
                return callback(
                  new Error(this.$t('common.rangeCustom', [1, 720]))
                );
              }
            },
            trigger: 'change',
          },
        ],
      },
    };
  },

  computed: {
    // ...mapState('User', ['tenantInfo']),
    ...mapState('PortalAuth', ['twillio']),
    ...mapState('PrivateCustomed', ['customedItem']),
  },

  async mounted() {
    // 私有云定制
    if (process.env.VUE_APP_MACC_CLOUD_ENV === 'private') {
      this.portalForm.redirectUrl = this.customedItem.portalPostLoginUrl;
    }

    if (this.twillio) {
      this.portalForm.sid = this.twillio.sid;
      this.portalForm.authToken = this.twillio.authToken;
      this.portalForm.authPhone = this.twillio.authPhone;
    }
    // await this.getTwillio();

    if (this.portalObj) {
      const { portalId, maccPortalInfo, smsInfo } = this.portalObj;
      this.editedPortalName = maccPortalInfo.name;

      if (![0, 15, 30, 60].includes(maccPortalInfo.accessTime)) {
        maccPortalInfo.accessTimeVal = maccPortalInfo.accessTime;
        maccPortalInfo.accessTime = -1;
      }

      this.portalForm = {
        portalId: portalId,
        portalName: maccPortalInfo.name,
        authType: maccPortalInfo.authType.split(','),
        accessTime: maccPortalInfo.accessTime,
        accessTimeVal: maccPortalInfo.accessTimeVal || 60,
        limitedTimes: maccPortalInfo.limitedTimes,
        displayStatistics:
          maccPortalInfo.displayStatistics === 'true' ? true : false,
        redirectUrl: maccPortalInfo.redirectUrl,
        sid: smsInfo.smsSid,
        authToken: smsInfo.smsToken,
        authPhone: smsInfo.smsFromPhoneNumber,
      };
    }
  },

  watch: {},
  components: { CommonPanel },
  methods: {
    // async getTwillio() {
    //   var data = {
    //     api: maccApi.GET_BAAS_DETAIL.replace(
    //       '{tenantName}',
    //       this.tenantInfo.tenantName
    //     ).replace('{tenantId}', this.tenantInfo.tenantId),
    //     method: 'GET',
    //   };
    //   let res = await requestHttp(data);
    //   console.log(res);
    //   if (res && res.code == 0) {
    //     this.portalForm.sid = res.smsSid;
    //     this.portalForm.authToken = res.smsToken;
    //     this.portalForm.authPhone = res.smsFromPhoneNumber;
    //   }
    // },

    onChangeAuthType(authTypes) {
      this.$EventBus.$emit('setAuthTypes', authTypes);
    },
    getConf() {
      const self = this;
      return new Promise((resolve) => {
        this.$refs.portalForm.validate((valid) => {
          let accessTime = this.portalForm.accessTime;
          if (accessTime === -1) {
            accessTime = Number(this.portalForm.accessTimeVal);
          }

          let res = {
            valid,
            ...this.portalForm,
            authType: this.portalForm.authType.join(','),
            accessTime,
          };
          resolve(res);
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.sub-form {
  padding: 0px 16px 0px 8px;
  box-sizing: border-box;
  background: #f7f8fa;
  border-radius: 4px;
  /deep/ .ant-form-item {
    margin-bottom: 0px;
  }
  /deep/ .ant-form-explain {
    margin-left: 29.16666667%;
  }
  /deep/ .ant-select,
  /deep/ .ant-input {
    width: 320px;
  }
}
.auth-type-cbx {
  width: 100%;
  .ant-checkbox-wrapper + .ant-checkbox-wrapper {
    margin-top: 8px;
    margin-left: 0;
  }
  div + .ant-checkbox-wrapper {
    margin-top: 8px;
  }
}
.text {
  margin: 0 4px 0 8px;
}
.des {
  font-family: 'Inter';
  font-style: normal;
  font-weight: 400;
  font-size: 12px;

  color: #4e5969;
  flex: none;
  order: 1;
  flex-grow: 0;
}
</style>
